package com.hundsun.epay.autosimu.api;

import java.util.ArrayList;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;

import com.hundsun.epay.autosimu.config.Channel;
import com.hundsun.epay.autosimu.config.ControllerField;
import com.hundsun.epay.autosimu.config.PayCorporation;
import com.hundsun.epay.autosimu.config.Trade;
import com.hundsun.epay.autosimu.internal.ObjectFactory;

public class PayCorporationIntrospector {
	private PayCorporation corporationConfig;

	public PayCorporationIntrospector(PayCorporation corporationConfig) {
		this.corporationConfig = corporationConfig;
	}
	
	public List<IntrospectedChannel> introspectChannels(Channel channel, Set<String> tradeIds){
		IntrospectedChannel introspectedChannel = ObjectFactory.createIntrospectedChannel(channel, corporationConfig);
		List<IntrospectedChannel> introspectedChannels = new ArrayList<IntrospectedChannel>();
		introspectedChannels.add(introspectedChannel);
		List<Trade> tradeToRun;
		if(tradeIds == null || tradeIds.isEmpty()){
			tradeToRun = channel.getTrades();
		}else{
			tradeToRun = new ArrayList<Trade>();
			for (Trade trade : channel.getTrades()) {
				if(tradeIds.contains(trade.getId())){
					tradeToRun.add(trade);
				}
			}
		}
		for (Trade trade : tradeToRun) {
			introspectedChannel.addIntrospectedTrade(ObjectFactory.createIntrospectedTrade(trade, channel, corporationConfig));
			for (Entry<String, ControllerField> entry : trade.getCfields().entrySet()) {
				introspectedChannel.addIntrospectedFieldControl(ObjectFactory.createIntrospectedFieldControl(entry.getValue(), trade, channel, corporationConfig));
			}
		}
		return introspectedChannels;
	}
}
